package com.spring.study.controller;


import com.spring.study.utils.MinioUtil;
import com.spring.study.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private MinioUtil minioUtil;

//    测试全局异常处理器
    @RequestMapping("/1")
    public int test1(){
        return 10/0;
    }


    public static boolean isImageFile(String fileName){
        return fileName.endsWith("jpg")
                || fileName.endsWith("png")
                || fileName.endsWith("jpeg")
                || fileName.endsWith("gif")
                || fileName.endsWith("bmp")
                || fileName.endsWith("webp");
    }
    //上传商品图片到minio
    @RequestMapping(value = "/up",method = RequestMethod.POST)
    public ResultUtil<String> upFile(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        String originalFilename = multipartFile.getOriginalFilename();
        log.info("文件名：{}",originalFilename);
        if (multipartFile.isEmpty()){
            return ResultUtil.error("200","文件不存在");
        }
        if (!isImageFile(originalFilename)){
            return ResultUtil.error("200","上传文件错误，请确认是否为图片");
        }
        String url = minioUtil.uploadFile(multipartFile.getInputStream(), multipartFile.getSize(), multipartFile.getOriginalFilename());
        return ResultUtil.success(url);
    }
}
